package com.dianqu.weather.core.service;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import net.sf.json.JSONObject;

import com.dianqu.weather.core.common.SystemConfig;
import com.dianqu.weather.core.common.Tools;
import com.dianqu.weather.core.dao.WeatherDao;
import com.dianqu.weather.core.entity.TWeather;
import com.dianqu.weather.core.model.WeatherInfo;
import com.dianqu.weather.web.engine.ContextStrategy;

@Service
public class WeatherService {
	private final Logger logger = Logger.getLogger(getClass());
	@Autowired
	private ContextStrategy contextStrategy;

	@Autowired
	private WeatherDao weatherDao;

	@Value("${differ}")
	private int differ;

	public String service(final String location) {
		if (Tools.isChinese(location)) {
			// query from datebase
			TWeather weather = weatherDao.getInfo(location);
			if (weather != null
					&& System.currentTimeMillis()
							- weather.getDatetime().getTime() <= differ) {
				return weather.getJsoninfo();
			} else // query from internet
			{
				final WeatherInfo info = contextStrategy.dosearch(location);
				// If the query to the information
				if (info != null) {
					JSONObject object = JSONObject.fromObject(info,
							Tools.jsonConfig());
					final String json = object.toString();
					// save is asynchronized
					new Thread() {
						public void run() {
							TWeather weather = new TWeather();
							weather.setDatetime(new Date());
							weather.setCityname(location);
							weather.setJsoninfo(json);
							weatherDao.saveInfo(weather);
						};
					}.start();
					return json;
				}
			}
		}
		// No weather information
		return SystemConfig.JSON_ERROR;
	}

}
